package cn.ztr.ymcc.service.impl;

import cn.ztr.ymcc.domain.Course;
import cn.ztr.ymcc.domain.CourseSummary;
import cn.ztr.ymcc.domain.CourseUserLearn;
import cn.ztr.ymcc.dto.PaySuccessDto;
import cn.ztr.ymcc.mapper.CourseMapper;
import cn.ztr.ymcc.mapper.CourseSummaryMapper;
import cn.ztr.ymcc.mapper.CourseUserLearnMapper;
import cn.ztr.ymcc.result.JsonResult;
import cn.ztr.ymcc.service.ICourseUserLearnService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ztr
 * @since 2023-02-27
 */
@Service
@Slf4j
public class CourseUserLearnServiceImpl extends ServiceImpl<CourseUserLearnMapper, CourseUserLearn> implements ICourseUserLearnService {

    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseSummaryMapper courseSummaryMapper;

    /**
     * 根据登录id和课程id
     * 查询用户购买课程记录
     * @param loginId
     * @param courseId
     * @return
     */
    @Override
    public JsonResult getLearnByLoginIdAndCourseId(Long loginId, Long courseId) {
        CourseUserLearn courseUserLearn = baseMapper.selectOne(new QueryWrapper<CourseUserLearn>().eq("login_id", loginId).eq("course_id", courseId));
        return JsonResult.me(courseUserLearn);
    }

    /**
     * 保存用户购买课程记录
     * @param paySuccessDto
     * @return
     */
    @Override
    @Transactional
    public boolean save(PaySuccessDto paySuccessDto) {
        //1 遍历购买的课程id
        for (Long courseId : paySuccessDto.getCourseIds()) {
            log.debug(courseId.toString());
            //2 查询课程信息
            Course course = courseMapper.selectById(courseId);
            //3 封装对象
            CourseUserLearn courseUserLearn = new CourseUserLearn()
                    .setCourseId(courseId)
                    .setCourseOrderNo(paySuccessDto.getCourseOrderNo())
                    .setLoginId(paySuccessDto.getLoginId())
                    .setStartTime(course.getStartTime())
                    .setEndTime(course.getEndTime());
            //4 添加购买信息
            baseMapper.insert(courseUserLearn);

            //课程销量+1
            CourseSummary courseSummary = courseSummaryMapper.selectById(courseId);
            courseSummary.setSaleCount(courseSummary.getSaleCount()+1);
            courseSummaryMapper.updateById(courseSummary);
        }
        return true;
    }
}
